package flst.ipiweb.struts.action.promotion;

import ipiwebprocess.ArticleProcess;
import ipiwebprocess.EnseigneProcess;
import ipiwebprocess.PromotionProcess;
import ipiwebprocess.TypePromotionProcess;
import ipiwebtransverse.Article;
import ipiwebtransverse.Enseigne;
import ipiwebtransverse.Promotion;
import ipiwebtransverse.TypePromotion;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class PromotionAction extends Action {

	private static PromotionProcess sPromotionProcess = new PromotionProcess();
	private static TypePromotionProcess sTypePromotionProcess = new TypePromotionProcess();
	private static EnseigneProcess sEnseigneProcess = new EnseigneProcess();
	private static ArticleProcess sArticleProcess = new ArticleProcess();
	
	public ActionForward execute(ActionMapping mapping, 
								ActionForm form,
								HttpServletRequest request, 
								HttpServletResponse response)
								throws Exception {

		PromotionFormAction vPromotionForm = (PromotionFormAction) form;
		
		Promotion vPromotion = new Promotion();

		vPromotion.setIdCode(vPromotionForm.getIdCodePromotion());

		String dateDebut = vPromotionForm.getAnneeDebutPromotion() + "-" + vPromotionForm.getMoisDebutPromotion() + "-" + vPromotionForm.getJourDebutPromotion();
		String dateFin = vPromotionForm.getAnneeFinPromotion() + "-" + vPromotionForm.getMoisFinPromotion() + "-" + vPromotionForm.getJourFinPromotion();
		
		vPromotion.setDateDebut(sPromotionProcess.stringToDate(dateDebut));
		vPromotion.setDateFin(sPromotionProcess.stringToDate(dateFin));
		
		// Pourcentage
		double pourcentage = vPromotionForm.getPourcentagePromotion() / 100;
		vPromotion.setPourcentage(pourcentage);
		
		// Article
		Article vArticle = sArticleProcess.GetArticleById(vPromotionForm.getReferenceArticlePromotion()); 
		vPromotion.setArticle(vArticle);

		// Type promotion
		TypePromotion vTypePromotion = sTypePromotionProcess.getTypePromotionById(vPromotionForm.getIdTypePromotion());
		vPromotion.setTypePromotion(vTypePromotion);

		// Enseigne
		Enseigne vEnseigne = sEnseigneProcess.GetEnseigneById(vPromotionForm.getIdEnseignePromotion());
		vPromotion.setEnseigne(vEnseigne);

		if (String.valueOf(vPromotionForm.getIdPromotion()).equals("0")) {
			sPromotionProcess.creerPromotion(vPromotion);
		} else {
			// Sinon on fait une modification
			vPromotion.setId(vPromotionForm.getIdPromotion());

			sPromotionProcess.modifierPromotion(vPromotion);
		}

		// On retourne la liste des Promotions
		request.setAttribute("listePromotion", sPromotionProcess.listerPromotion());
		
		return mapping.findForward("promotion_ok");
		
	}
}
